package br.edu.unilasalle.simon_test.util;

import java.net.MalformedURLException;
import java.net.URL;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class FireFoxDriverManager implements SeleniumDriverManager {

	private static String SELENIUM_DRIVER_MODE = "selenium.driver_mode";
	private static String SELENIUM_REMOTE_ADDRESS = "selenium.REMOTE.address";

	/**
	 * Inicializa o driver do selenium, que pode ser local ou remoto de acordo
	 * com a propriedade definida pela chave selenium.driver_mode
	 */
	public static WebDriver initSeleniumWebDriver() {
		try {
			return useRemoteDriver() ? createRemoteDriver() : createLocalDriver();
		} catch (Exception e) {
			throw new IllegalStateException("Não foi possível iniciar o driver do Selenium. Erro: " + e.getMessage(), e);
		}
	}

	/**
	 * Cria um driver local, utilizando o firefox como browser
	 */
	private static WebDriver createLocalDriver() {
		return new FirefoxDriver();
	}

	/**
	 * Cria um driver remoto, utilizando o firefox como browser
	 */
	private static WebDriver createRemoteDriver() throws MalformedURLException {
		String address = Utils.getTestProperty(SELENIUM_REMOTE_ADDRESS);
		DesiredCapabilities capabilities = DesiredCapabilities.firefox();
		capabilities.setCapability("nativeEvents", false);
		//capabilities.setPlatform(Platform.LINUX); // Descomentar esta linha se for utilizado no Linux
		return new RemoteWebDriver(new URL(address), capabilities);
	}

	/**
	 * @return <code>true</code> caso o driver remoto deva ser utilizado
	 */
	public static boolean useRemoteDriver() {
		return SeleniumDriverMode.REMOTE == SeleniumDriverMode.valueOf(Utils.getTestProperty(SELENIUM_DRIVER_MODE));
	}

}
